package algorithm.leetcode.simple;

/**
 * 给定一个链表，删除链表的倒数第 n 个节点，并且返回链表的头结点。
 *
 * @author jack.wu
 * @version 1.0
 * @date 2020/8/26
 */
public class Question19 {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        Question19 question = new Question19();
        ListNode head = question.removeNthFromEnd(node1, 2);
        System.out.println(head);
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null || n == 0) {
            return head;
        }
        ListNode pre = new ListNode(0);
        pre.next = head;
        int len = 0;
        ListNode cur = head;
        while (cur != null) {
            len++;
            cur = cur.next;
        }
        if (n > len){
            return null;
        }
        int realLen = len - n;
        cur = pre;
        while (realLen > 0){
            realLen--;
            cur = cur.next;
        }
        cur.next = cur.next.next;
        return pre.next;
    }

    private static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }

}


